<template>
    <!-- template标签下要包含一个div标签，给这个标签一个类名container -->
    <div class="container">
        <!-- 这里使用elementplus的布局容器，上面导航栏，下面显示主要内容 -->
        <el-container class="el-container">
            <!-- 导航栏 -->
            <el-header class="el-header">
                <div class="headerleft">
                    <div class="logo"><img src="../assets/logo.png" alt="" height="100%"></div>
                    <p class="navbtn" @click="goHome"><el-icon>
                            <House />
                        </el-icon>&nbsp;首页</p>
                    <p class="navbtn" @click="goHot"><el-icon>
                            <Loading />
                        </el-icon>&nbsp;热搜</p>
                    <p class="navbtn" @click="goNotice"><el-icon>
                            <Message />
                        </el-icon>&nbsp;公告</p>
                    <p class="navbtn" @click="goTask"><el-icon>
                            <Finished />
                        </el-icon>&nbsp;任务</p>
                </div>
                <div class="headercenter">
                    __<el-icon>
                        <CollectionTag />
                    </el-icon>发布__
                </div>
                <div class="headerright">
                    <div class="person" @click="goPersonal">
                        <el-icon>
                            <User />
                        </el-icon>个人
                    </div>
                </div>
            </el-header>

            <!-- 主要内容 -->
            <el-main class="el-main">
                <el-tabs type="border-card" class="el-tabs" @tab-change="onChangeTab" v-model="activeTab">

                    <!-- 发布文章 -->
                    <el-tab-pane label="发布文章" :name="tabsName[0]" class="el-tab-pane">
                        <div class="submitbtn">
                            <el-button type="primary" @click="submitArticle">确认发布</el-button>
                        </div>
                        <div class="inputtitle">
                            文章标题:
                            <el-input class="input" v-model="articleTitle"></el-input>
                        </div>
                        <div class="inputinfo">
                            作者:
                            <el-input class="input" v-model="articleAuthor" disabled></el-input>
                        </div>
                        <div class="inputdetail">
                            文章内容:
                            <div id="editorArticle">
                                <!-- 这里放置富文本编辑器 -->
                                使用说明
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 发布任务 -->
                    <el-tab-pane label="发布任务" :name="tabsName[1]" class="el-tab-pane">
                        <el-scrollbar height="100%">
                            <div class="submitbtn">
                                <el-button type="primary" @click="submitTask">确认发布</el-button>
                            </div>
                            <div class="inputtitle">
                                任务标题:
                                <el-input class="input" v-model="taskTitle"></el-input>
                            </div>
                            <div class="inputinfo">
                                发布者:
                                <el-input class="input" v-model="taskAuthor" disabled></el-input>
                                联系方式:
                                <el-input class="input" v-model="taskContact"></el-input>
                            </div>
                            <div class="inputdetail">
                                任务内容:
                                <el-input v-model="taskContent" :autosize="{ minRows: 4 }" type="textarea" resize="none" />
                            </div>
                            <div class="inputimage">
                                添加图片:
                                <div class="image-upload-container">
                                    <!-- 图片显示区 -->
                                    <div class="image-list">
                                        <div v-for="(img, index) in taskImgShowList" :key="index" class="image-item">
                                            <img :src="img.purl" alt="上传图片" />
                                            <button class="delete-btn" @click="removeImage(index)">×</button>
                                        </div>
                                    </div>

                                    <!-- 拖拽上传区域 -->
                                    <div class="upload-area" @dragover.prevent @drop.prevent="handleDrop" @click="triggerFileSelect">
                                        <input type="file" accept="image/*" @change="handleFileSelect" ref="fileInput"
                                            hidden />
                                        <p>拖拽图片到此处，或 <span>点击选择图片</span></p>
                                    </div>
                                </div>

                            </div>
                        </el-scrollbar>
                    </el-tab-pane>
                </el-tabs>

            </el-main>
        </el-container>
    </div>
</template>
<script setup>
import router from '../router'
import { ref } from 'vue'
import { onMounted } from 'vue';
import { userStore } from '../stores/userStore.js'
import api from '../api/api.js'
import { ElMessage } from 'element-plus'


// 代码块高亮
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
window.hljs = hljs

// 数据定义
//选项卡名称
const tabsName = ref(['article', 'task'])
//当前激活的选项卡
const activeTab = ref(tabsName.value[0])
// 文章标题
const articleTitle = ref('')
// 文章作者
const articleAuthor = ref('')
// 文章内容
const articleContent = ref(null)
//文章图片列表
const articleImgList = ref([])
//当前编辑的文章id
const articleId = ref(0)
// 任务标题
const taskTitle = ref('')
// 任务作者
const taskAuthor = ref('')
// 联系方式
const taskContact = ref('')
// 任务内容
const taskContent = ref('')
// 任务图片列表
const taskImgList = ref([])
const taskImgShowList = ref([])



//获取用户信息
const userInfo = userStore()
const { nickname } = userInfo;

//文章内容更新函数
function updateHTML(html) {
    //保存文章内容到变量中
    articleContent.value = html
}

//获取当前编辑文章的id
const getArticleId = async () => {
    try {
        const res = await api.getNewArticleIdApi({ uid: userInfo.userid })
        articleId.value = res.data.aid;
    } catch (error) {
        console.error(error)
    }
}

//点击切换标签页
const onChangeTab = async (TabName) => {
    activeTab.value = TabName

    //重新获取文章id
    await getArticleId();
}

//提交文章内容
const submitArticle = async () => {
    try {
        if (!articleTitle.value || !articleContent.value) {
            ElMessage.warning('标题和内容不能为空')
            return;
        }
        const res = await api.commitArticleApi({
            aid: articleId.value,
            articleTitle: articleTitle.value,
            uid: userInfo.userid,
            name: articleAuthor.value,
            content: articleContent.value,
            tid: 1,
            imgList: articleImgList.value
        })
        if (res.code === 200) {
            ElMessage.success('发布成功')
            router.push('/login/my-articles')
        }
    } catch (error) {
        console.error(error)
    }
}
//提交任务内容
const submitTask = async () => {
    try {
        if (!taskTitle.value || !taskContent.value || !taskContact.value) {
            ElMessage.warning('标题、内容和联系方式不能为空')
            return;
        }
        //处理任务内容
        let finalContent = "<p>联系方式:" + taskContact.value + "</p>";
        finalContent += "<p>" + taskContent.value + "</p><br>";
        let listlength = taskImgShowList.value.length;
        for (let i = 0; i < listlength; i++) {
            finalContent += '<img src="' + taskImgShowList.value[i].purl + '" alt="上传图片" width="300px" height="auto"><br>';
        }
        const res = await api.commitArticleApi({
            aid: articleId.value,
            articleTitle: taskTitle.value,
            uid: userInfo.userid,
            name: taskAuthor.value,
            content: finalContent,
            tid: 3,
            imgList: taskImgList.value
        })
        if (res.code === 200) {
            ElMessage.success('发布成功')
            router.push('/login/my-tasks')
        }

    } catch (error) {
        console.error(error)
    }
}


// 路由跳转
const goHome = () => {
    router.push('/')
}
const goHot = () => {
    router.push('/hotsearch')
}
const goNotice = () => {
    router.push('/notice')
}
const goTask = () => {
    router.push('/task')
}
const goPersonal = () => {
    router.push('/login')
}


// 富文本编辑器
let editorArticle


// 富文本编辑器配置
const TOOLBAR_CONFIG = [
    ['undo', 'redo', 'clean'],
    [{ header: [1, 2, 3, false] }, { color: [] }, 'bold', 'italic', 'strike', 'underline'],
    [{ list: 'ordered' }, { list: 'bullet' },],
    ['link', 'blockquote', 'code', 'code-block', 'image'],
    ['fullscreen'],
]

// 富文本编辑器初始化
onMounted(async () => {
    // ssr compat, reference: https://vitepress.dev/guide/ssr-compat#importing-in-mounted-hook
    import('@opentiny/fluent-editor').then((module) => {
        const FluentEditor = module.default

        editorArticle = new FluentEditor('#editorArticle', {
            theme: 'snow',
            modules: {
                toolbar: TOOLBAR_CONFIG,
                syntax: true,
            },
            uploadOption: {
                imageUpload: ({ file, callback }) => {
                    imageHandler(file, (imageUrl) => {
                        // 调用 callback，传入 imageUrl 即可实现图片渲染
                        callback({
                            code: 0,
                            message: 'Upload success!',
                            data: {
                                imageUrl,
                            },
                        })
                    })
                },
            },
        })
        updateHTML(editorArticle.root.innerHTML)

        editorArticle.on('text-change', () => {
            updateHTML(editorArticle.root.innerHTML)
        })
    })

    //文章作者信息初始化
    articleAuthor.value = nickname;
    taskAuthor.value = nickname;
    //获取文章id
    await getArticleId();

})

// 图片上传================
/**
 * 上传图片到服务器
 * @param image File 格式的图片
 * @param callback 回调函数，用来处理服务器返回的图片 URL
 * 除了 XMLHttpRequest，也可以使用 fetch / axios 等工具实现图片上传。
 */
async function imageHandler(image, callback) {
    const data = new FormData()
    data.append('file', image)
    data.append('aid', articleId.value)
    try {
        console.log("文章id", articleId.value)
        // const response = await axios.post(IMG_API_URL, data);
        const response = await api.uploadImgApi(data);

        // 图片上传成功，就直接返回图片 URL
        callback(response.data.purl)

        const pid = response.data.pid;
        const purl = response.data.purl;
        const aid = articleId.value;
        const uid = userInfo.userid;
        articleImgList.value.push({ pid, purl, uid, aid })

    } catch (error) {
        console.error(error)
        // 图片上传失败了，就转成 Base64 格式
        const reader = new FileReader()
        reader.onload = function (e) {
            callback(e.target.result)
        }
        reader.readAsDataURL(image)

    }
}


//========================任务图片上传逻辑
// 处理文件选择
const handleFileSelect = async (event) => {
    const file = event.target.files[0];
    if (file) {
        await uploadImage(file);
    }
    event.target.value = ""; // 清空选择器的值以支持重复选择同一文件
};

// 处理拖拽
const handleDrop = async (event) => {
    const file = event.dataTransfer.files[0];
    if (file) {
        await uploadImage(file);
    }
};

// 上传图片
const uploadImage = async (file) => {
    try {

        

        const data = new FormData()
        data.append('file', file)
        data.append('aid', articleId.value)
        const result = await api.uploadImgApi(data);

        const pid = result.data.pid;
        const purl = result.data.purl;
        const aid = articleId.value;
        const uid = userInfo.userid;
        taskImgList.value.push({ pid, purl, uid, aid })
        taskImgShowList.value.push({ pid, purl, uid, aid });

    } catch (error) {
        console.error("上传失败", error);
    }
};

// 删除图片
const removeImage = (index) => {
    taskImgShowList.value.splice(index, 1);
};

// 触发文件选择
const fileInput = ref(null);
const triggerFileSelect = () => {
    fileInput.value.click();
};


</script>

<style scoped lang="less">
.container {
    width: 100%;
    height: 100vh;

    .el-container {
        height: 100%;

        .el-header {
            background-image: linear-gradient(to right, #fefefe, #ffffff, #409eff);
            margin: 0;
            padding: 0;
            height: 6%;
            display: flex;
            align-items: center;
            justify-content: flex-start;

            .headerleft {
                height: 100%;
                display: flex;
                align-items: center;
                width: 45%;
                font-size: 20px;

                .logo {
                    height: 100%;
                    margin-left: 10px;
                    border-radius: 50%;
                    overflow: hidden;
                }

                .navbtn {
                    margin-left: 10px;
                    user-select: none;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    padding: 0 10px;

                    &:hover {
                        background-color: #40a0ffa5;
                    }
                }
            }

            .headercenter {
                height: 100%;
                width: 10%;

                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 20px;
                color: #40a0ff;
                font-weight: bold;
            }

            .headerright {
                height: 100%;
                width: 45%;
                display: flex;
                align-items: center;
                justify-content: flex-end;

                .person {
                    user-select: none;
                    height: 80%;
                    font-size: 20px;
                    display: flex;
                    align-items: center;
                    margin-right: 10px;
                    padding: 0 10px;
                    border-radius: 25px;

                    &:hover {
                        background-color: #abd5ff;

                    }
                }
            }
        }

        .el-main {
            background-color: #f7f7f7;
            margin: 0;
            padding: 0;
            height: 94%;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding-top: 20px;

            .el-tabs {

                width: 90%;

                .el-tab-pane {

                    padding: 0 20px;

                    .inputdetail {
                        height: 100%;

                        #editorArticle{
                            min-height: 400px;
                        }
                        

                    }

                    .selectbtn {
                        height: 65px;
                    }
                }
            }

        }
    }
}

.image-upload-container {
    width: 100%;
    margin: 20px auto;
    text-align: center;
}

.image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    justify-content: flex-start;
}

.image-item {
    position: relative;
    width: 100px;
    height: 100px;
    overflow: hidden;
    border: 1px solid #ddd;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.image-item img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.delete-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(255, 0, 0, 0.8);
    color: white;
    border: none;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.delete-btn:hover {
    background: red;
}

.upload-area {
    border: 2px dashed #007bff;
    border-radius: 10px;
    padding: 20px;
    color: #666;
    cursor: pointer;
    transition: border-color 0.3s;
}

.upload-area:hover {
    border-color: #0056b3;
}

.upload-area span {
    color: #007bff;
    text-decoration: underline;
    cursor: pointer;
}
</style>